package com.seio.edc.controller.system;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.alibaba.fastjson.JSON;
import com.nova.edc.model.system.*;
import com.nova.edc.service.system.DescriptionService;
import com.seio.edc.common.Constants;
import com.seio.edc.util.IntegerUtils;
import org.apache.http.HttpRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.nova.edc.service.system.GroupService;
import com.nova.edc.service.system.LoginTypeService;
import com.nova.edc.service.system.RoleService;
import com.nova.frame.dao.pager.Page;
import com.nova.frame.dao.pager.PageList;
import com.nova.frame.utils.DateUtils;
import com.nova.frame.utils.StringUtils;
import com.seio.edc.common.MD5;
import com.seio.edc.controller.core.BaseContoller;

@Controller
@RequestMapping(value = "/system/login")
public class LoginContronller extends BaseContoller {

    @Autowired
    private com.nova.edc.service.system.LoginService novaLoginService;
    @Autowired
    private com.nova.edc.service.system.CustomerInfoService novaCustomerInfoService;
    @Autowired
    private GroupService novaGroupService;
    @Autowired
    private RoleService novaRoleService;
    @Autowired
    private LoginTypeService novaLoginTypeService;
    @Autowired
    private DescriptionService novaDescriptionService;

    private final int PAGE_SIZE = 10;

    /**
     * 用户表页面初始化
     *
     * @param request
     * @param modelMap
     * @return
     */
    @RequestMapping(value = "loginList.shtml")
    public ModelAndView loginList(HttpServletRequest request,
                                  HttpSession session, ModelMap modelMap, Integer pageIndex,
                                  @ModelAttribute("login") Login login) {
        // 当前页数
        Page page = new Page();
        page.setCurrentPage(pageIndex == null || pageIndex == 0 ? 1 : pageIndex);
        page.setPageSize(PAGE_SIZE);
        modelMap.put("pageIndex", page.getCurrentPage());
        Login sessionLogin = (Login) session.getAttribute("sessionLogin");
        novaLoginService.trimLogin(login);
        PageList<Login> pageList = novaLoginService.findLoginPageList(login,
                page, "ord asc, AddDate", "desc", sessionLogin);
        List<Login> loginList = pageList.getDatas();
        novaDescriptionService.getDescription(loginList);
        modelMap.put("dataCount", page.getRowCount());
        modelMap.put("pageCount", page.getTotalPage());
        // 数据列表
        modelMap.put("list", loginList);
        modelMap.put("login", login);

        return new ModelAndView("system/loginList", modelMap);
    }

    /**
     * 查看代理商下级数据
     */
    @RequestMapping(value = "agentLoginList.shtml")
    public ModelAndView agentLoginList(HttpServletRequest request,
                                       HttpSession session, ModelMap modelMap, Integer pageIndex,
                                       Integer loginId, String username) {
        // 当前页数
        Page page = new Page();
        page.setCurrentPage(pageIndex == null || pageIndex == 0 ? 1 : pageIndex);
        page.setPageSize(PAGE_SIZE);
        modelMap.put("pageIndex", page.getCurrentPage());
        PageList<Login> pageList = novaLoginService.findAgentLoginPageList(
                loginId, page, "ord asc, AddDate", "desc", username);
        modelMap.put("dataCount", page.getRowCount());
        modelMap.put("pageCount", page.getTotalPage());
        modelMap.put("loginId", loginId);

        // 数据列表
        modelMap.put("list", pageList.getDatas());

        return new ModelAndView("system/agentLoginList", modelMap);
    }

    /**
     * 编辑登录信息初始化
     */
    @RequestMapping(value = "editLoginInit.shtml")
    public ModelAndView editLoginInit(HttpServletRequest request,
                                      HttpSession session, ModelMap modelMap, Integer id) {
        Integer roleId = (Integer) session
                .getAttribute(ModelConstant.SESSION_ROLEID);
        String loginName = (String) session
                .getAttribute(ModelConstant.SESSION_LOGINNAME);
        if (id != null && id != 0) {
            Login login = novaLoginService.getById(id);
            modelMap.put("login", login);
            modelMap.put("customerList", JSON.toJSONString(novaCustomerInfoService.findAllCusomerName()));
            modelMap.put("groupList", JSON.toJSONString(novaGroupService.findAllGroupName()));

        } else {
            modelMap.put("customerList", JSON.toJSONString(novaCustomerInfoService.findAllCusomerName()));
            modelMap.put("groupList", JSON.toJSONString(novaGroupService.findAllGroupName()));

        }
        // 所有集团的list
        modelMap.put("commonRole", ModelConstant.ROLE_COMMON);
        modelMap.put("groupRole", ModelConstant.ROLE_GROUP);
        return new ModelAndView("system/loginEdit", modelMap);
    }

    /**
     * 添加login
     */
    @RequestMapping(value = "save.shtml")
    public ModelAndView save(@ModelAttribute("login") Login login,
                             HttpSession session, HttpServletRequest request, ModelMap modelMap, Integer roletype) {
        Login sessionLogin = (Login) session.getAttribute("sessionLogin");
        if (StringUtils.isNotNullOrEmpty(login.getPassword())) {
            login.setPassword(MD5.Md5(login.getPassword()));
        } else {
            login.setPassword(null);
        }
        if (StringUtils.isNotNullOrEmpty(login.getGroupname())) {
            int groupId = novaGroupService.getByGroupName(login.getGroupname()).getId();
            login.setGroupid(groupId);

        }
        if (StringUtils.isNotNullOrEmpty(login.getCustomername())) {
            int companyId = novaCustomerInfoService.findIdByName(login.getCustomername());
            CustomerInfo customerInfo = novaCustomerInfoService.getById(companyId);
            Group groupCode = novaGroupService.getByGroupCode(customerInfo.getGroupcode());
            login.setGroupid(groupCode.getId());
            login.setCustomerinfoid(companyId);
        }
        login.setRoleid(novaRoleService.findByType(login.getRoletype()).get(0).getId());
        if (login.getId() != null && login.getId() != 0) {
            novaLoginService.emptyCompanyByid(login.getId());
            login.setModifyby(sessionLogin.getUsername());
            login.setModifydate(DateUtils.getCurrentDate());
            login.setModifystamp(DateUtils.getCurrentDate());
            novaLoginService.update(login);
        } else {
            login.setRoleid(novaRoleService.findByType(roletype).get(0).getId());
            login.setScrapped(0);
            login.setAdddate(DateUtils.getCurrentDate());
            login.setAddby(sessionLogin.getUsername());
            login.setParentid(sessionLogin.getId());
            novaLoginService.insert(login);
        }

        return loginList(request, session, modelMap, null, new Login());

    }

    @RequestMapping(value = "delete.shtml")
    public ModelAndView delete(int id, HttpServletRequest request,
                               HttpSession session, ModelMap modelMap, @ModelAttribute("login") Login login) {
        novaLoginService.deleteById(id);
        return loginList(request, session, modelMap, null, login);
    }

    @RequestMapping(value = "userNameVali.shtml")
    @ResponseBody
    public Map<String, Object> userNameVali(HttpServletRequest request,
                                            String userName, Integer loginId) {
        Map<String, Object> map = new HashMap<String, Object>();
        // String userName = (String) param.get("userName");
        // Integer loginId = (Integer) param.get("loginId");
        map.put("existFlag", novaLoginService.isExistLogin(userName, loginId));
        return map;
    }

    @RequestMapping(value = "getCompanyListByGroup.shtml")
    @ResponseBody
    public Map<String, Object> getCompanyListByGroup(
            HttpServletRequest request, HttpSession session,
            @RequestBody String groupcode) {
        Login login = (Login) session.getAttribute("sessionLogin");
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("companyList", novaCustomerInfoService
                .findCustomerInfoByGroupAndLogin(
                        StringUtils.isNullOrEmpty(groupcode) ? null
                                : StringUtils.tryParseInt(groupcode), login
                                .getUsername()));
        return map;
    }

    @RequestMapping(value = "loginMessageInit.shtml")
    public ModelAndView loginMessageInit(HttpServletRequest request, HttpSession session,
                                         ModelMap modelMap, Integer loginid) {
        Login login = novaLoginService.getById(loginid);
        int customerInfoID = 0;
        if (ModelConstant.ROLE_COMMON == login.getRoletype()) {
            customerInfoID = login.getCustomerinfoid();
        } else if (ModelConstant.ROLE_GROUP == login.getRoletype()) {
            customerInfoID = login.getGroupid();
        }
        Description description = novaDescriptionService.getByCustomerInfoId(customerInfoID);
        request.getSession().setAttribute("descriptionname", login.getUsername());
        request.getSession().setAttribute("uploadpath", Constants.UploadDescriptionPath);
        request.getSession().setAttribute("uploadurl", Constants.UploadDescriptionUrl);
        modelMap.put("description", description);
        modelMap.put("login", login);
        return new ModelAndView("system/loginMessageInit", modelMap);
    }

    @RequestMapping(value = "editLoginMessage.shtml")
    public ModelAndView editLoginMessage(HttpServletRequest request, HttpSession session,
                                         ModelMap modelMap, Description description, Integer loginid) {
        Login sessionLogin = (Login) session.getAttribute("sessionLogin");
        description.setModifyby(sessionLogin.getUsername());
        description.setModifydate(DateUtils.getCurrentDate());
        description.setModifystamp(DateUtils.getCurrentDate());
        if (!IntegerUtils.isEmptyAndNull(description.getScrapped())) {
            description.setScrapped(0);
        }
        if (description.getId() == null) {
            Login login = novaLoginService.getById(loginid);
            if (ModelConstant.ROLE_COMMON == login.getRoletype()) {
                description.setCustomerinfoid(login.getCustomerinfoid());
            } else if (ModelConstant.ROLE_GROUP == login.getRoletype()) {
                description.setCustomerinfoid(login.getGroupid());
            }
            description.setAddby(sessionLogin.getUsername());
            description.setAdddate(DateUtils.getCurrentDate());
            description.setDatastorageid(2);
            novaDescriptionService.insert(description);
        } else {
            novaDescriptionService.update(description);
        }
        return loginList(request, session, modelMap, null, new Login());
    }

    @RequestMapping(value = "upLoadImage.shtml")
    public ModelAndView upLoadDocuments(@RequestParam(value = "uploadfile", required = false) MultipartFile uploadfile, Integer loginid, ModelMap modelMap) {
        int name = 0;
        Login login = novaLoginService.getById(loginid);
        if (ModelConstant.ROLE_GROUP == login.getRoletype()) {
            name = login.getGroupid();
        } else {
            name = login.getCustomerinfoid();
        }
        System.out.print(this.getClass().getClassLoader().getResource(".").getPath());
//        try {
//            if (uploadfile != null) {
//                String fileName = uploadfile.getOriginalFilename();
//                File newfile = new File(Constants.UploadDocumentsPath + "\\"+ name + fileName);
//                uploadfile.transferTo(newfile);
//            }
//            modelMap.put("msg", "文件上传成功");
//        } catch (IOException e) {
//            modelMap.put("msg", "文件上传成功");
//            e.printStackTrace();
//        }
        return null;
    }
}
